package src.leetcode.hot.mid_0105;

import java.util.HashMap;
import java.util.Map;

public class buildTree {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.buildTree(new int[]{3,9,20,15,7}, new int[]{9,3,15,20,7}));
    }
}


class Solution {
    private Map<Integer, Integer> indexMap;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        indexMap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            indexMap.put(inorder[i], i);
        }
        return buildTree(preorder, inorder, 0, preorder.length, 0, inorder.length);
    }

    private TreeNode buildTree(int[] preorder, int[] inorder, int start_pre, int end_pre, int start_ino, int end_ino) {
        if (start_pre >= end_pre) return null;
        int index = indexMap.get(preorder[start_pre]);
        int left_num = index - start_ino;
        TreeNode node = new TreeNode(inorder[index]);
        node.left = buildTree(preorder,  inorder, start_pre + 1,            start_pre + left_num + 1, start_ino, index);
        node.right = buildTree(preorder, inorder, start_pre + left_num + 1, end_pre,                  index + 1,     end_ino);
        return node;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
